/**
 * 文档路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 处理项目文档展示相关的路由，支持Markdown文档渲染、代码高亮、目录生成等功能
 * @date 2025年9月27日
 */

const express = require('express');
const fs = require('fs');
const path = require('path');
const { marked } = require('marked');
const hljs = require('highlight.js');

const router = express.Router();

// 配置 marked 以支持代码高亮和标题ID
const renderer = new marked.Renderer();

// 自定义标题渲染，确保ID符合CSS规范
renderer.heading = function(token) {
  // 从token中提取信息
  const level = token.depth;
  const text = token.text;
  
  // 确保text是字符串
  const textStr = String(text || '');
  // 提取标题文本（去除HTML标签）
  const cleanText = textStr.replace(/<[^>]*>/g, '');
  let id = cleanText.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-');
  
  // 确保ID以字母开头，符合CSS选择器规范
  if (id && /^[0-9]/.test(id)) {
    id = 'section-' + id;
  }
  
  return `<h${level} id="${id}">${textStr}</h${level}>`;
};

marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value;
      } catch (__) {}
    }
    return hljs.highlightAuto(code).value;
  },
  langPrefix: 'hljs language-',
  breaks: true,
  gfm: true,
  headerIds: true,
  headerPrefix: '',
  renderer: renderer
});

// 获取文档目录路径
const DOCS_DIR = path.join(__dirname, '..', 'docs');

// 安全文件名验证函数（支持子目录路径）
function isSafeFilename(filename) {
  // 支持类似：api-docs/userAPI.md, model-docs/userModel.md 等格式
  return /^[a-zA-Z0-9_\-\/]+\.md$/.test(filename);
}

// 递归读取docs目录及其子目录中的所有.md文件
function getDocFiles() {
  try {
    const files = [];
    
    function readDirRecursive(dir, basePath = '') {
      const items = fs.readdirSync(dir);
      
      items.forEach(item => {
        const fullPath = path.join(dir, item);
        const relativePath = path.join(basePath, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory()) {
          // 递归读取子目录
          readDirRecursive(fullPath, relativePath);
        } else if (item.endsWith('.md')) {
          // 添加相对路径，用于URL和显示
          files.push(relativePath.replace(/\\/g, '/')); // 统一使用正斜杠
        }
      });
    }
    
    readDirRecursive(DOCS_DIR);
    return files;
  } catch (error) {
    console.error('读取文档目录失败:', error);
    return [];
  }
}

// 解析markdown文件内容，提取标题
function parseMarkdownContent(content) {
  // 统一换行符，处理Windows(\r\n)和Mac(\r)换行符
  const normalizedContent = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
  const lines = normalizedContent.split('\n');
  const headings = [];
  let title = '';
  
  lines.forEach(line => {
    // 去除行尾空白字符
    const cleanLine = line.trim();
    
    // 提取标题
    if (cleanLine.startsWith('# ')) {
      title = cleanLine.replace('# ', '').trim();
    }
    
    // 提取所有标题
    const match = cleanLine.match(/^(#{1,6})\s+(.+)$/);
    if (match) {
      const level = match[1].length;
      const text = match[2].trim();
      let id = text.toLowerCase().replace(/[^\w\u4e00-\u9fa5]+/g, '-');
      
      // 确保ID以字母开头，符合CSS选择器规范
      if (id && /^[0-9]/.test(id)) {
        id = 'section-' + id;
      }
      
      headings.push({ level, text, id });
    }
  });
  
  return { title, headings };
}

// 生成侧边栏HTML（包含tab切换功能和文件夹折叠）
function generateSidebarHTML(currentFile = '', headings = []) {
  const files = getDocFiles();
  
  // 按文件夹分组文件
  const folderStructure = {};
  files.forEach(file => {
    const pathParts = file.split('/');
    if (pathParts.length > 1) {
      // 有子目录
      const folder = pathParts.slice(0, -1).join('/');
      const filename = pathParts[pathParts.length - 1];
      if (!folderStructure[folder]) {
        folderStructure[folder] = [];
      }
      folderStructure[folder].push(filename);
    } else {
      // 根目录文件
      if (!folderStructure['__root__']) {
        folderStructure['__root__'] = [];
      }
      folderStructure['__root__'].push(file);
    }
  });
  
  let sidebarHTML = '<div class="sidebar-tabs">';
  sidebarHTML += '<div class="tab-buttons">';
  sidebarHTML += '<button class="tab-button active" data-tab="files">📁 文档列表</button>';
  sidebarHTML += '<button class="tab-button" data-tab="toc">📑 目录导航</button>';
  sidebarHTML += '</div>';
  
  // 文档列表内容
  sidebarHTML += '<div class="tab-content active" id="files-tab">';
  sidebarHTML += '<div class="sidebar-section">';
  sidebarHTML += '<ul class="file-list">';
  
  // 生成文件夹和文件结构
  Object.keys(folderStructure).sort().forEach(folder => {
    if (folder === '__root__') {
      // 根目录文件
      folderStructure[folder].forEach(filename => {
        const file = filename;
        const isActive = file === currentFile ? 'active' : '';
        const fileName = filename.replace('.md', '');
        const fileIcon = getFileIcon(fileName);
        sidebarHTML += `<li class="file-item"><a href="/docs/${file}" class="${isActive}">${fileIcon} ${fileName}</a></li>`;
      });
    } else {
      // 文件夹
      const folderName = folder.split('/').pop();
      const folderIcon = folderName.includes('api') ? '🔌' : 
                        folderName.includes('model') ? '📊' : 
                        folderName.includes('status') ? '📋' : '📁';
      
      sidebarHTML += `<li class="folder-item">`;
      sidebarHTML += `<div class="folder-header" onclick="toggleFolder('${folder}')">`;
      sidebarHTML += `<span class="folder-icon" id="folder-icon-${folder}">📁</span>`;
      sidebarHTML += `<span class="folder-name">${folderName}</span>`;
      sidebarHTML += `<span class="folder-toggle" id="folder-toggle-${folder}">▶</span>`;
      sidebarHTML += `</div>`;
      sidebarHTML += `<ul class="folder-files" id="folder-${folder}">`;
      
      folderStructure[folder].forEach(filename => {
        const file = `${folder}/${filename}`;
        const isActive = file === currentFile ? 'active' : '';
        const fileName = filename.replace('.md', '');
        const fileIcon = getFileIcon(fileName);
        sidebarHTML += `<li class="file-item"><a href="/docs/${file}" class="${isActive}">${fileIcon} ${fileName}</a></li>`;
      });
      
      sidebarHTML += '</ul></li>';
    }
  });
  
  sidebarHTML += '</ul></div></div>';
  
  // 目录导航内容
  sidebarHTML += '<div class="tab-content" id="toc-tab">';
  sidebarHTML += generateTOC(headings);
  sidebarHTML += '</div>';
  
  sidebarHTML += '</div>';
  
  return sidebarHTML;
}

// 根据文件名获取图标
function getFileIcon(filename) {
  const icons = {
    'readme': '📖',
    'guide': '📚',
    'api': '🔌',
    'tutorial': '🎓',
    'faq': '❓',
    'changelog': '🔄'
  };
  
  const lowerName = filename.toLowerCase();
  for (const [key, icon] of Object.entries(icons)) {
    if (lowerName.includes(key)) {
      return icon;
    }
  }
  
  return '📄';
}

// 生成目录导航HTML
function generateTOC(headings) {
  if (headings.length === 0) {
    return '<div class="toc-empty"><p>📝 暂无目录导航</p><p class="toc-hint">文档中的标题将显示在这里</p></div>';
  }
  
  let tocHTML = '<div class="toc"><h3>📑 目录导航</h3><ul class="toc-list">';
  
  headings.forEach(heading => {
    const indentClass = `toc-level-${heading.level}`;
    const headingIcon = getHeadingIcon(heading.level);
    tocHTML += `<li class="${indentClass}"><a href="#${heading.id}">${headingIcon} ${heading.text}</a></li>`;
  });
  
  tocHTML += '</ul>';
  // 添加键盘导航提示
  tocHTML += '<div class="keyboard-hint">💡 <kbd>Alt</kbd> + <kbd>↑</kbd>/<kbd>↓</kbd> 键盘导航</div>';
  tocHTML += '</div>';
  return tocHTML;
}

// 根据标题级别获取图标
function getHeadingIcon(level) {
  // 使用更美观的图标替代 # 符号
  const icons = ['📄', '📋', '📊', '📝', '🔗', '⚙️'];
  return icons[level - 1] || '•';
}

// 统一模板函数
function getUnifiedTemplate({ title, sidebarHTML, contentHTML, currentFile }) {
  return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title} - 文档中心</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/styles/github-dark.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/highlight.min.js"></script>
    <style>
        :root {
            --primary-color: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-light: #dbeafe;
            --bg-color: #f8fafc;
            --sidebar-bg: #ffffff;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --text-muted: #94a3b8;
            --border-color: #e2e8f0;
            --border-light: #f1f5f9;
            --shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            --radius: 8px;
            --radius-lg: 12px;
            --transition: all 0.2s ease-in-out;
        }
        
        .dark-mode {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
            --primary-light: #1e3a8a;
            --bg-color: #0f172a;
            --sidebar-bg: #1e293b;
            --text-primary: #f1f5f9;
            --text-secondary: #cbd5e1;
            --text-muted: #64748b;
            --border-color: #334155;
            --border-light: #1e293b;
            --shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.3);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: var(--text-primary);
            background: var(--bg-color);
            transition: var(--transition);
        }
        
        .container {
            display: flex;
            min-height: 100vh;
            max-width: 1600px;
            margin: 0 auto;
            background: var(--sidebar-bg);
            box-shadow: var(--shadow-lg);
            position: relative;
        }
        
        .sidebar {
            width: 320px;
            background: var(--sidebar-bg);
            border-right: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            transition: var(--transition);
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            z-index: 100;
        }
        
        /* Tab 样式 */
        .sidebar-tabs {
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        /* 侧边栏折叠状态 */
        .sidebar.collapsed {
            width: 60px;
        }
        
        .sidebar.collapsed .sidebar-tabs {
            overflow: hidden;
        }
        
        .sidebar.collapsed .tab-buttons,
        .sidebar.collapsed .tab-content {
            display: none;
        }
        
        .sidebar.collapsed .sidebar-toggle {
            display: block;
            position: absolute;
            top: 50%;
            right: -15px;
            transform: translateY(-50%);
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            box-shadow: var(--shadow);
            font-size: 14px;
            z-index: 101;
        }
        
        .sidebar-toggle {
            display: none;
        }
        
        /* 主内容区域在侧边栏折叠时的调整 */
        .main-content.sidebar-collapsed {
            max-width: calc(100% - 60px);
            margin-left: 60px;
        }
        
        .tab-content {
            display: none;
            flex: 1;
            overflow-y: auto;
            padding: 0;
            max-height: calc(100vh - 60px); /* 减去tab按钮的高度 */
        }
        
        .tab-content.active {
            display: block;
        }
        
        .tab-buttons {
            display: flex;
            background: var(--sidebar-bg);
            border-bottom: 1px solid var(--border-color);
            padding: 8px;
            gap: 4px;
        }
        
        .tab-button {
            flex: 1;
            padding: 10px 12px;
            border: none;
            background: transparent;
            color: var(--text-secondary);
            cursor: pointer;
            transition: var(--transition);
            font-size: 13px;
            font-weight: 500;
            border-radius: var(--radius);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .tab-button:hover {
            background: var(--border-light);
            color: var(--text-primary);
        }
        
        .tab-button.active {
            background: var(--primary-color);
            color: white;
            box-shadow: var(--shadow);
        }
        
        .sidebar-section {
            padding: 20px;
        }
        
        .file-list {
            list-style: none;
        }
        
        .file-list li {
            margin-bottom: 4px;
        }
        
        .file-list a {
            display: flex;
            align-items: center;
            padding: 10px 12px;
            color: var(--text-secondary);
            text-decoration: none;
            border-radius: var(--radius);
            transition: var(--transition);
            font-weight: 500;
            gap: 10px;
        }
        
        .file-list a:hover {
            background: var(--primary-light);
            color: var(--primary-dark);
            transform: translateX(2px);
        }
        
        .file-list a.active {
            background: var(--primary-color);
            color: white;
            font-weight: 600;
            box-shadow: var(--shadow);
        }
        
        /* 文件夹和文件项样式 */
        .folder-item {
            margin-bottom: 4px;
        }
        
        .folder-header {
            display: flex;
            align-items: center;
            padding: 10px 12px;
            cursor: pointer;
            border-radius: var(--radius);
            transition: var(--transition);
            user-select: none;
        }
        
        .folder-header:hover {
            background: var(--border-light);
        }
        
        .folder-icon {
            margin-right: 8px;
            font-size: 1.1em;
            transition: transform 0.2s ease;
        }
        
        .folder-name {
            flex: 1;
            font-weight: 500;
            color: var(--text-primary);
        }
        
        .folder-toggle {
            font-size: 0.8em;
            color: var(--text-muted);
            transition: transform 0.2s ease;
        }
        
        .folder-files {
            list-style: none;
            margin-left: 24px;
            margin-top: 4px;
            margin-bottom: 8px;
            display: block;
            transition: all 0.3s ease;
        }
        
        .folder-files.collapsed {
            display: none;
        }
        
        .folder-item.collapsed .folder-toggle {
            transform: rotate(-90deg);
        }
        
        /* 展开状态时的旋转效果 */
        .folder-item:not(.collapsed) .folder-toggle {
            transform: rotate(0deg);
        }
        
        /* 三角箭头旋转动画 */
        .folder-toggle {
            transition: transform 0.3s ease;
        }
        
        .file-item {
            margin-bottom: 2px;
        }
        
        .main-content {
            flex: 1;
            padding: 0;
            max-width: calc(100% - 320px);
            display: flex;
            flex-direction: column;
            margin-left: 320px;
        }
        
        .content-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 40px 50px 30px;
            margin-bottom: 0;
        }
        
        .content-header h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 8px;
            background: linear-gradient(45deg, #ffffff, #e0f2fe);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .content-header .doc-path {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .markdown-body {
            flex: 1;
            padding: 40px 50px;
            max-width: 900px;
            margin: 0 auto;
            width: 100%;
        }
        
        /* Markdown 内容样式 */
        .markdown-body h1 {
            color: var(--text-primary);
            margin: 40px 0 20px 0;
            font-size: 2rem;
            font-weight: 700;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--border-color);
        }
        
        .markdown-body h2 {
            color: var(--text-primary);
            margin: 35px 0 18px 0;
            font-size: 1.6rem;
            font-weight: 600;
        }
        
        .markdown-body h3 {
            color: var(--text-primary);
            margin: 30px 0 15px 0;
            font-size: 1.3rem;
            font-weight: 600;
        }
        
        .markdown-body p {
            margin-bottom: 16px;
            color: var(--text-secondary);
            line-height: 1.7;
        }
        
        .markdown-body code {
            background: var(--border-light);
            color: var(--primary-dark);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', monospace;
            font-size: 0.85em;
            font-weight: 500;
        }
        
        .markdown-body pre {
            background: #1a1a1a;
            padding: 20px;
            border-radius: var(--radius-lg);
            overflow-x: auto;
            margin: 24px 0;
            border-left: 4px solid var(--primary-color);
            box-shadow: var(--shadow);
        }
        
        .markdown-body pre code {
            background: none;
            padding: 0;
            color: #f8f8f2;
        }
        
        .markdown-body ul, .markdown-body ol {
            margin: 16px 0 16px 30px;
            color: var(--text-secondary);
        }
        
        .markdown-body li {
            margin-bottom: 8px;
            line-height: 1.6;
        }
        
        .markdown-body blockquote {
            border-left: 4px solid var(--primary-color);
            padding: 16px 20px;
            margin: 24px 0;
            background: var(--primary-light);
            border-radius: 0 var(--radius) var(--radius) 0;
            color: var(--text-primary);
        }
        
        .markdown-body table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: var(--shadow);
            border-radius: var(--radius);
            overflow: hidden;
        }
        
        .markdown-body th, .markdown-body td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }
        
        .markdown-body th {
            background: var(--primary-light);
            font-weight: 600;
            color: var(--primary-dark);
        }
        
        .markdown-body tr:hover {
            background: var(--border-light);
        }
        
        /* TOC 样式 */
        .toc {
            background: var(--sidebar-bg);
            border-radius: var(--radius);
            padding: 20px;
        }
        
        .toc h3 {
            color: var(--text-primary);
            margin-bottom: 15px;
            font-size: 1.1rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .toc-list {
            list-style: none;
            /* 移除高度限制，让目录导航可以自由扩展 */
            /* max-height: 400px; */
            /* overflow-y: auto; */
        }
        
        .toc-list li {
            margin: 6px 0;
            transition: var(--transition);
        }
        
        .toc-list a {
            color: var(--text-secondary);
            text-decoration: none;
            transition: var(--transition);
            display: block;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 0.9rem;
        }
        
        .toc-list a:hover {
            color: var(--primary-color);
            background: var(--border-light);
            transform: translateX(2px);
        }
        
        /* 目录导航高亮样式 */
        .toc-list a.active {
            font-weight: 600 !important;
            color: var(--primary-color) !important;
            background-color: var(--primary-light) !important;
            border-left: 3px solid var(--primary-color) !important;
            transform: translateX(4px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .dark-mode .toc-list a.active {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }
        
        .toc-level-2 { padding-left: 15px; }
        .toc-level-3 { padding-left: 30px; }
        .toc-level-4 { padding-left: 45px; }
        .toc-level-5 { padding-left: 60px; }
        .toc-level-6 { padding-left: 75px; }
        
        .toc-empty {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-muted);
        }
        
        .toc-hint {
            font-size: 0.8rem;
            margin-top: 8px;
        }
        
        /* 键盘导航提示 */
        .keyboard-hint {
            font-size: 0.75rem;
            color: var(--text-muted);
            margin-top: 15px;
            padding: 10px;
            background: var(--border-light);
            border-radius: var(--radius);
            text-align: center;
            opacity: 0.8;
            transition: var(--transition);
        }
        
        .keyboard-hint:hover {
            opacity: 1;
        }
        
        .keyboard-hint kbd {
            background: var(--bg-color);
            border: 1px solid var(--border-color);
            border-radius: 3px;
            padding: 2px 6px;
            font-family: monospace;
            font-size: 0.7rem;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            margin: 0 2px;
        }
        
        .dark-mode .keyboard-hint kbd {
            background: var(--sidebar-bg);
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }
        
        /* 主题切换按钮 */
        .theme-toggle {
            position: absolute;
            top: 20px;
            right: 20px;
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 12px;
            border-radius: 50%;
            cursor: pointer;
            transition: var(--transition);
            box-shadow: var(--shadow);
            z-index: 1000;
        }
        
        .theme-toggle:hover {
            background: var(--primary-dark);
            transform: scale(1.1);
        }
        
        /* 响应式设计 */
        @media (max-width: 1024px) {
            .container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
                left: auto;
                top: auto;
                height: auto;
            }
            
            .sidebar.collapsed {
                width: 100%;
                height: 50px;
            }
            
            .sidebar.collapsed .sidebar-toggle {
                right: 20px;
                top: 10px;
                transform: none;
            }
            
            .main-content {
                max-width: 100%;
                margin-left: 0;
            }
            
            .main-content.sidebar-collapsed {
                max-width: 100%;
                margin-left: 0;
            }
            
            .content-header, .markdown-body {
                padding: 30px;
            }
        }
        
        @media (max-width: 768px) {
            .content-header h1 {
                font-size: 2rem;
            }
            
            .content-header, .markdown-body {
                padding: 20px;
            }
            
            .tab-buttons {
                flex-direction: column;
            }
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .markdown-body > * {
            animation: fadeIn 0.3s ease-out;
        }
        
        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: var(--border-light);
        }
        
        ::-webkit-scrollbar-thumb {
            background: var(--text-muted);
            border-radius: 3px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: var(--text-secondary);
        }
    </style>
</head>
<body>
    <button class="theme-toggle" onclick="toggleTheme()">🌓</button>
    
    <div class="container">
        <aside class="sidebar" id="sidebar">
            ${sidebarHTML}
            <button class="sidebar-toggle" id="sidebar-toggle" onclick="toggleSidebar()">◀</button>
        </aside>
        
        <main class="main-content" id="main-content">
            <div class="content-header">
                <h1>${title}</h1>
                <div class="doc-path">
                    <span>📁</span>
                    <span>文档中心 / ${currentFile ? currentFile.replace('.md', '') : '首页'}</span>
                </div>
            </div>
            
            <div class="markdown-body">
                ${contentHTML}
            </div>
        </main>
    </div>
    
    <script>
        // Tab切换功能
        function initTabs() {
            const tabButtons = document.querySelectorAll('.tab-button');
            const tabContents = document.querySelectorAll('.tab-content');
            
            tabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const targetTab = this.getAttribute('data-tab');
                    
                    // 移除所有active类
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    // 添加active类到当前选中的tab
                    this.classList.add('active');
                    document.getElementById(targetTab + '-tab').classList.add('active');
                    
                    // 保存tab状态
                    localStorage.setItem('activeTab', targetTab);
                });
            });
            
            // 恢复tab状态
            const savedTab = localStorage.getItem('activeTab') || 'files';
            const savedButton = document.querySelector(\`[data-tab="\${savedTab}"]\`);
            if (savedButton) {
                savedButton.click();
            }
        }
        
        // 主题切换功能
        function toggleTheme() {
            document.body.classList.toggle('dark-mode');
            const isDark = document.body.classList.contains('dark-mode');
            localStorage.setItem('theme', isDark ? 'dark' : 'light');
            updateThemeButton();
        }
        
        function updateThemeButton() {
            const button = document.querySelector('.theme-toggle');
            const isDark = document.body.classList.contains('dark-mode');
            button.textContent = isDark ? '🌞' : '🌓';
        }
        
        // 初始化主题
        function initTheme() {
            const savedTheme = localStorage.getItem('theme') || 'light';
            if (savedTheme === 'dark') {
                document.body.classList.add('dark-mode');
            }
            updateThemeButton();
        }
        
        // 防抖函数，优化性能
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        // 平滑滚动到锚点（优化版）
        function initSmoothScroll() {
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    const targetId = this.getAttribute('href');
                    const target = document.querySelector(targetId);
                    
                    if (target) {
                        // 计算滚动位置，考虑固定头部和间距
                        const headerOffset = 80; // 头部固定元素的高度
                        const elementPosition = target.getBoundingClientRect().top;
                        const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                        
                        // 使用更平滑的滚动动画
                        window.scrollTo({
                            top: offsetPosition,
                            behavior: 'smooth'
                        });
                        
                        // 更新URL哈希（不触发滚动）
                        history.pushState(null, null, targetId);
                        
                        // 立即高亮当前标题
                        setTimeout(() => highlightCurrentHeading(), 300);
                    }
                });
            });
        }
        
        // 高亮当前标题（增强版）
        function highlightCurrentHeading() {
            // 支持更多级别的标题
            const headings = document.querySelectorAll('.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6');
            const tocLinks = document.querySelectorAll('.toc-list a');
            
            if (headings.length === 0) return;
            
            // 获取当前滚动位置，考虑偏移量
            const scrollPosition = window.scrollY + 120; // 增加偏移量
            let currentHeading = headings[0];
            
            // 找到当前视口中的标题
            headings.forEach(heading => {
                if (heading.offsetTop <= scrollPosition) {
                    currentHeading = heading;
                }
            });
            
            // 重置所有链接样式
            tocLinks.forEach(link => {
                link.classList.remove('active');
                link.style.fontWeight = 'normal';
                link.style.color = '';
                link.style.backgroundColor = '';
                link.style.borderLeft = '';
            });
            
            // 高亮当前标题
            const activeLink = document.querySelector('.toc-list a[href="#' + currentHeading.id + '"]');
            if (activeLink) {
                activeLink.classList.add('active');
                activeLink.style.fontWeight = '600';
                activeLink.style.color = 'var(--primary-color)';
                activeLink.style.backgroundColor = 'var(--primary-light)';
                activeLink.style.borderLeft = '3px solid var(--primary-color)';
                
                // 确保当前高亮的目录项在视口中
                const tocContainer = document.querySelector('.toc-list');
                if (tocContainer) {
                    const linkRect = activeLink.getBoundingClientRect();
                    const containerRect = tocContainer.getBoundingClientRect();
                    
                    if (linkRect.top < containerRect.top || linkRect.bottom > containerRect.bottom) {
                        activeLink.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                    }
                }
            }
        }
        
        // 键盘导航支持
        function initKeyboardNavigation() {
            document.addEventListener('keydown', function(e) {
                // Alt + 方向键导航
                if (e.altKey) {
                    const tocLinks = Array.from(document.querySelectorAll('.toc-list a'));
                    const activeLink = document.querySelector('.toc-list a.active');
                    const currentIndex = activeLink ? tocLinks.indexOf(activeLink) : -1;
                    
                    if (e.key === 'ArrowDown' && currentIndex < tocLinks.length - 1) {
                        e.preventDefault();
                        tocLinks[currentIndex + 1].click();
                    } else if (e.key === 'ArrowUp' && currentIndex > 0) {
                        e.preventDefault();
                        tocLinks[currentIndex - 1].click();
                    }
                }
            });
        }
        
        // 初始化代码高亮
        function initCodeHighlight() {
            // 检查是否存在需要高亮的代码块
            const codeBlocks = document.querySelectorAll('pre code');
            
            if (codeBlocks.length > 0) {
                // 尝试使用highlight.js进行语法高亮
                if (typeof hljs !== 'undefined') {
                    codeBlocks.forEach((block) => {
                        if (!block.classList.contains('hljs')) {
                            try {
                                // 获取语言类型
                                const className = block.className;
                                let language = null;
                                
                                if (className.includes('language-')) {
                                    language = className.replace('language-', '');
                                } else if (className.includes('lang-')) {
                                    language = className.replace('lang-', '');
                                }
                                
                                // 如果检测到语言且highlight.js支持该语言
                                if (language && hljs.getLanguage(language)) {
                                    hljs.highlightElement(block);
                                } else if (!language) {
                                    // 如果没有指定语言，使用自动检测
                                    hljs.highlightElement(block);
                                }
                            } catch (error) {
                                console.error('代码块高亮失败:', error);
                            }
                        }
                    });
                } else {
                    // 尝试动态加载highlight.js
                    loadHighlightJS();
                }
            }
        }
        
        // 动态加载highlight.js
        function loadHighlightJS() {
            if (typeof hljs === 'undefined') {
                const script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/highlight.min.js';
                script.onload = function() {
                    // 加载常用语言包
                    loadCommonLanguages();
                };
                script.onerror = function() {
                    console.error('highlight.js 动态加载失败');
                };
                document.head.appendChild(script);
            }
        }
        
        // 加载常用语言包
        function loadCommonLanguages() {
            const languages = ['javascript', 'json', 'python', 'css', 'html'];
            let loadedCount = 0;
            
            languages.forEach(lang => {
                const script = document.createElement('script');
                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/languages/' + lang + '.min.js';
                script.onload = function() {
                    loadedCount++;
                    if (loadedCount === languages.length) {
                        initCodeHighlight();
                    }
                };
                script.onerror = function() {
                    loadedCount++;
                    if (loadedCount === languages.length) {
                        initCodeHighlight();
                    }
                };
                document.head.appendChild(script);
            });
        }
        
        // 侧边栏折叠功能
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('main-content');
            const toggleBtn = document.getElementById('sidebar-toggle');
            
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('sidebar-collapsed');
            
            // 更新按钮图标
            if (sidebar.classList.contains('collapsed')) {
                toggleBtn.textContent = '▶';
            } else {
                toggleBtn.textContent = '◀';
            }
            
            // 保存状态到localStorage
            const isCollapsed = sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebarCollapsed', isCollapsed);
        }
        
        // 恢复侧边栏状态
        function restoreSidebarState() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('main-content');
            const toggleBtn = document.getElementById('sidebar-toggle');
            const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
            
            if (isCollapsed) {
                sidebar.classList.add('collapsed');
                mainContent.classList.add('sidebar-collapsed');
                toggleBtn.textContent = '▶';
            }
        }
        
        // 文件夹折叠功能
        function toggleFolder(folderId) {
            const folderFiles = document.getElementById('folder-' + folderId);
            const folderItem = folderFiles.closest('.folder-item');
            const folderIcon = document.getElementById('folder-icon-' + folderId);
            const folderToggle = document.getElementById('folder-toggle-' + folderId);
            
            if (folderFiles.classList.contains('collapsed')) {
                // 展开文件夹
                folderFiles.classList.remove('collapsed');
                folderItem.classList.remove('collapsed');
                folderIcon.textContent = '📂';  // 展开状态用打开的文件夹
                folderToggle.textContent = '▼'; // 展开状态三角朝下
            } else {
                // 折叠文件夹（恢复初始状态）
                folderFiles.classList.add('collapsed');
                folderItem.classList.add('collapsed');
                folderIcon.textContent = '📁';  // 折叠状态用关闭的文件夹
                folderToggle.textContent = '▶'; // 折叠状态三角朝右
            }
            
            // 保存折叠状态到localStorage
            const collapsedFolders = JSON.parse(localStorage.getItem('collapsedFolders') || '[]');
            if (folderFiles.classList.contains('collapsed')) {
                if (!collapsedFolders.includes(folderId)) {
                    collapsedFolders.push(folderId);
                }
            } else {
                const index = collapsedFolders.indexOf(folderId);
                if (index > -1) {
                    collapsedFolders.splice(index, 1);
                }
            }
            localStorage.setItem('collapsedFolders', JSON.stringify(collapsedFolders));
        }
        
        // 恢复文件夹折叠状态
        function restoreFolderState() {
            const collapsedFolders = JSON.parse(localStorage.getItem('collapsedFolders') || '[]');
            collapsedFolders.forEach(folderId => {
                const folderFiles = document.getElementById('folder-' + folderId);
                if (folderFiles) {
                    const folderItem = folderFiles.closest('.folder-item');
                    const folderIcon = document.getElementById('folder-icon-' + folderId);
                    const folderToggle = document.getElementById('folder-toggle-' + folderId);
                    
                    folderFiles.classList.add('collapsed');
                    folderItem.classList.add('collapsed');
                    if (folderIcon) folderIcon.textContent = '📁';  // 初始状态用关闭的文件夹
                    if (folderToggle) folderToggle.textContent = '▶'; // 初始状态三角朝右
                }
            });
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initTabs();
            initTheme();
            initSmoothScroll();
            initKeyboardNavigation();
            
            // 恢复侧边栏状态
            restoreSidebarState();
            
            // 恢复文件夹状态
            restoreFolderState();
            
            // 延迟初始化代码高亮，确保highlight.js完全加载
            setTimeout(() => {
                initCodeHighlight();
            }, 100);
        });
        
        // 页面加载完成后也尝试初始化代码高亮
        window.addEventListener('load', function() {
            setTimeout(() => {
                initCodeHighlight();
            }, 500); // 更长的延迟确保所有资源加载完成
            
            // 使用防抖函数优化滚动性能
            window.addEventListener('scroll', debounce(highlightCurrentHeading, 50));
            highlightCurrentHeading();
            
            // 监听URL哈希变化（浏览器前进/后退）
            window.addEventListener('hashchange', function() {
                const hash = window.location.hash;
                if (hash) {
                    const target = document.querySelector(hash);
                    if (target) {
                        setTimeout(() => {
                            const headerOffset = 80;
                            const elementPosition = target.getBoundingClientRect().top;
                            const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                            
                            window.scrollTo({
                                top: offsetPosition,
                                behavior: 'smooth'
                            });
                            highlightCurrentHeading();
                        }, 100);
                    }
                }
            });
            
            // 页面加载时处理URL哈希
            if (window.location.hash) {
                setTimeout(() => {
                    const target = document.querySelector(window.location.hash);
                    if (target) {
                        const headerOffset = 80;
                        const elementPosition = target.getBoundingClientRect().top;
                        const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
                        
                        window.scrollTo({
                            top: offsetPosition,
                            behavior: 'smooth'
                        });
                        highlightCurrentHeading();
                    }
                }, 500);
            }
        });
    </script>
</body>
</html>`;
}

// 根路径 - 文档列表页面
router.get('/', (req, res) => {
  try {
    const files = getDocFiles();
    
    // 按文件夹分组文件
    const folderStructure = {};
    files.forEach(file => {
      const pathParts = file.split('/');
      if (pathParts.length > 1) {
        // 有子目录
        const folder = pathParts.slice(0, -1).join('/');
        const filename = pathParts[pathParts.length - 1];
        if (!folderStructure[folder]) {
          folderStructure[folder] = [];
        }
        folderStructure[folder].push(filename);
      } else {
        // 根目录文件
        if (!folderStructure['__root__']) {
          folderStructure['__root__'] = [];
        }
        folderStructure['__root__'].push(file);
      }
    });
    
    let contentHTML = `
      <div style="text-align: center; margin-bottom: 40px;">
        <h1>📚 文档中心</h1>
        <p style="color: var(--text-secondary); font-size: 1.1rem;">欢迎访问文档中心，这里汇集了所有技术文档和指南</p>
      </div>
      <div class="doc-grid">
    `;
    
    // 按文件夹显示文档
    Object.keys(folderStructure).sort().forEach(folder => {
      if (folder === '__root__') {
        // 根目录文件
        folderStructure[folder].forEach(filename => {
          const file = filename;
          const fileName = filename.replace('.md', '');
          const fileIcon = getFileIcon(fileName);
          
          contentHTML += `
            <div class="doc-card">
              <div class="doc-icon">${fileIcon}</div>
              <h3><a href="/docs/${file}">${fileName}</a></h3>
              <p>${file}</p>
              <a href="/docs/${file}" class="doc-link">阅读文档 →</a>
            </div>
          `;
        });
      } else {
        // 文件夹
        const folderName = folder.split('/').pop();
        const folderIcon = folderName.includes('api') ? '🔌' : 
                          folderName.includes('model') ? '📊' : 
                          folderName.includes('status') ? '📋' : '📁';
        
        contentHTML += `
          <div class="doc-folder">
            <div class="folder-header">
              <div class="folder-icon">${folderIcon}</div>
              <h3>${folderName}</h3>
              <span class="file-count">${folderStructure[folder].length} 个文档</span>
            </div>
            <div class="folder-files">
        `;
        
        folderStructure[folder].forEach(filename => {
          const file = `${folder}/${filename}`;
          const fileName = filename.replace('.md', '');
          const fileIcon = getFileIcon(fileName);
          
          contentHTML += `
            <div class="doc-card folder-card">
              <div class="doc-icon">${fileIcon}</div>
              <h4><a href="/docs/${file}">${fileName}</a></h4>
              <a href="/docs/${file}" class="doc-link">阅读文档 →</a>
            </div>
          `;
        });
        
        contentHTML += '</div></div>';
      }
    });
    
    if (files.length === 0) {
      contentHTML += `
        <div style="text-align: center; padding: 60px 20px; color: var(--text-muted);">
          <div style="font-size: 3rem; margin-bottom: 20px;">📁</div>
          <h3>暂无文档</h3>
          <p>请将Markdown文档放入docs目录</p>
        </div>
      `;
    }
    
    contentHTML += '</div>';
    
    // 添加卡片样式
    contentHTML += `
      <style>
        .doc-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
          gap: 24px;
          margin-top: 30px;
        }
        
        .doc-card {
          background: var(--sidebar-bg);
          border: 1px solid var(--border-color);
          border-radius: var(--radius-lg);
          padding: 24px;
          transition: var(--transition);
          box-shadow: var(--shadow);
        }
        
        .doc-card:hover {
          transform: translateY(-2px);
          box-shadow: var(--shadow-lg);
          border-color: var(--primary-color);
        }
        
        .doc-icon {
          font-size: 2rem;
          margin-bottom: 16px;
        }
        
        .doc-card h3 {
          margin-bottom: 12px;
        }
        
        .doc-card h3 a {
          color: var(--text-primary);
          text-decoration: none;
        }
        
        .doc-card h3 a:hover {
          color: var(--primary-color);
        }
        
        .doc-card p {
          color: var(--text-secondary);
          margin-bottom: 16px;
          font-size: 0.9rem;
        }
        
        .doc-link {
          color: var(--primary-color);
          text-decoration: none;
          font-weight: 500;
          display: inline-flex;
          align-items: center;
          gap: 4px;
        }
        
        .doc-link:hover {
          color: var(--primary-dark);
        }
        
        /* 文件夹样式 */
        .doc-folder {
          background: var(--sidebar-bg);
          border: 2px solid var(--border-color);
          border-radius: var(--radius-lg);
          padding: 24px;
          margin-bottom: 24px;
          transition: var(--transition);
        }
        
        .doc-folder:hover {
          border-color: var(--primary-color);
          box-shadow: var(--shadow-lg);
        }
        
        .doc-folder .folder-header {
          display: flex;
          align-items: center;
          margin-bottom: 20px;
          padding-bottom: 16px;
          border-bottom: 1px solid var(--border-light);
        }
        
        .doc-folder .folder-icon {
          font-size: 2rem;
          margin-right: 16px;
        }
        
        .doc-folder h3 {
          margin: 0;
          flex: 1;
          color: var(--text-primary);
        }
        
        .doc-folder .file-count {
          color: var(--text-muted);
          font-size: 0.9rem;
          font-weight: 500;
        }
        
        .doc-folder .folder-files {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
          gap: 16px;
        }
        
        .doc-folder .folder-card {
          margin: 0;
          padding: 20px;
          border: 1px solid var(--border-light);
        }
        
        .doc-folder .folder-card:hover {
          transform: translateY(-1px);
          border-color: var(--primary-color);
        }
        
        .doc-folder .folder-card h4 {
          margin-bottom: 8px;
          font-size: 1.1rem;
        }
      </style>
    `;
    
    const sidebarHTML = generateSidebarHTML('', []);
    const html = getUnifiedTemplate({
      title: '文档中心',
      sidebarHTML,
      contentHTML,
      currentFile: ''
    });
    
    res.send(html);
  } catch (error) {
    console.error('文档列表页面错误:', error);
    res.status(500).send('服务器错误');
  }
});

// 具体文档页面
router.get('/:filename(*)', (req, res) => {
  const { filename } = req.params;
  
  // 验证文件名安全性
  if (!isSafeFilename(filename)) {
    return res.status(400).send('无效的文件名');
  }
  
  const filePath = path.join(DOCS_DIR, filename);
  
  try {
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).send('文档不存在');
    }
    
    // 读取文件内容
    const content = fs.readFileSync(filePath, 'utf8');
    
    // 解析markdown内容
    const { title, headings } = parseMarkdownContent(content);
    
    // 转换markdown为HTML，marked会自动处理标题ID
    let contentHTML = marked(content);
    
    // 生成带tab的侧边栏（包含目录导航）
    const sidebarHTML = generateSidebarHTML(filename, headings);
    
    const html = getUnifiedTemplate({
      title: title || filename.replace('.md', ''),
      sidebarHTML,
      contentHTML,
      currentFile: filename
    });
    
    res.send(html);
  } catch (error) {
    console.error('文档页面错误:', error);
    res.status(500).send('服务器错误');
  }
});

module.exports = router;